package Servlet;


import Dao.UserDao;
import Model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@WebServlet("/UserPassWordChangeServlet")
public class UserPassWordChangeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 从请求体中读取JSON数据
        StringBuilder jsonStringBuilder = new StringBuilder();
        String line;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            while ((line = reader.readLine()) != null) {
                jsonStringBuilder.append(line);
            }
        } catch (Exception e) {
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("status", "error");
            jsonResponse.put("message", "请求格式错误或服务器内部错误！");
            response.getWriter().print(jsonResponse.toString());
            return;
        }

        String jsonString = jsonStringBuilder.toString();
        JSONObject jsonObject = new JSONObject(jsonString);

        String usedpassword = jsonObject.getString("usedpassword");
        String nowpassword = jsonObject.getString("nowpassword");
        String nowpassword1 = jsonObject.getString("nowpassword1");

        HttpSession session = request.getSession(false);
        Integer ID = (Integer) session.getAttribute("UserID");
        User model = new User(ID, usedpassword);
        if (UserDao.selectExist(model) && nowpassword.equals(nowpassword1)) {
            session.setAttribute("UserPassword", nowpassword);
            User pat1 = new User(ID, nowpassword);
            if (UserDao.updateUserKey(pat1)) {
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("status", "success");
                jsonResponse.put("message", "密码修改成功！");
                response.getWriter().print(jsonResponse.toString());
            } else {
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("status", "error");
                jsonResponse.put("message", "密码修改失败！");
                response.getWriter().print(jsonResponse.toString());
            }
        } else {
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("status", "error");
            jsonResponse.put("message", "原密码不正确或新密码不一致！");
            response.getWriter().print(jsonResponse.toString());
        }
    }
}